using System;
using System.Windows.Forms;
using System.Drawing;

namespace Shrapnel
{
    internal class Grid
    {
        /// <summary>
        /// Whether or not this grid is visible.
        /// </summary>
        private bool visible = true;

        /// <summary>
        /// The size of this grid in pixels
        /// </summary>
        private float size = 32.0f;


		/// <summary>
		/// Shows or hides this grid.
		/// </summary>
		public bool Visible
		{
			get { return visible; }
			set { visible = value; }
		}

        /// <summary>
        /// Gets or sets the size of this grid in pixels
        /// </summary>
        public float Size
        {
            get { return size; }
            set { size = value; }
        }

        /// <summary>
        /// Draws this grid.
        /// </summary>
        /// <param name="e">The painting event arguments.</param>
        public void Draw(PaintEventArgs e, ViewState viewState)
        {
            // Let's create the grid size, it has to be 1 at least.
            float zoomedGridSize = size * viewState.ZoomFactor;
            zoomedGridSize = (zoomedGridSize > 1.0f) ? zoomedGridSize : 1.0f;

            PointF startingPosition = viewState.Offset;

            if (startingPosition.X > 0)
                startingPosition.X %= zoomedGridSize;
            else
                startingPosition.X = zoomedGridSize - ((-startingPosition.X) % zoomedGridSize);

            if (startingPosition.Y > 0)
                startingPosition.Y %= zoomedGridSize;
            else
                startingPosition.Y = zoomedGridSize - ((-startingPosition.Y) % zoomedGridSize);

            using (Pen pen = new Pen(Color.LightGray))
            {
                for (float x = startingPosition.X; x < e.ClipRectangle.Width; x += zoomedGridSize)
                    e.Graphics.DrawLine(pen, x, 0, x, e.ClipRectangle.Height);

                for (float y = startingPosition.Y; y < e.ClipRectangle.Height; y += zoomedGridSize)
                    e.Graphics.DrawLine(pen, 0, y, e.ClipRectangle.Width, y);
            }
        }
    }
}
